//
//  EditDPDetailViewController.m
//  TimeManager
//
//  Created by 刘凯敏 on 04/12/2016.
//  Copyright © 2016 刘凯敏. All rights reserved.
//

#import "EditDPDetailViewController.h"
#import "DPDetailModel.h"

@implementation EditDPDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.nameField.text = self.contactModel.name;
    self.placeField.text = self.contactModel.place;
    //添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.placeField];
}

-(void) textChange{
    //修改按钮状态
    //    if(self.nameField.text.length && self.pwdField.text.length){
    //        self.loginBtn.enabled = YES;
    //    }
    //    else {
    //        self.loginBtn.enabled = NO;
    //    }
    //等价于
    self.saveBtn.enabled = (self.nameField.text.length && self.placeField.text.length);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//保存
- (IBAction)saveAction:(id)sender {
    //1.关闭当前页面
    [self.navigationController popViewControllerAnimated:YES];
    //2.通知代理
    //如果协议相应了方法
    if([self.delegate respondsToSelector:@selector(editContact:didSaveContact:)]){
        //更新数据模型
        self.contactModel.name = self.nameField.text;
        self.contactModel.place = self.placeField.text;
        [self.delegate editContact:self didSaveContact:self.contactModel];
    }
}
//"编辑"和"保存"按钮状态的改变
- (IBAction)editAction:(UIBarButtonItem *)sender {
    if(self.nameField.enabled){
        self.nameField.enabled = NO;
        self.placeField.enabled = NO;
        [self.view endEditing:YES];
        self.saveBtn.hidden = YES;
        sender.title = @"编辑";
        //还原回原来的数据
        self.nameField.text = self.contactModel.name;
        self.placeField.text = self.contactModel.place;
    }
    else{
        self.nameField.enabled = YES;
        self.placeField.enabled = YES;
        [self.view endEditing: YES];
        self.saveBtn.hidden = NO;
        sender.title = @"取消";
    }
}

//触碰背景关闭键盘
- (IBAction)backTap:(id)sender {
    //让nameField控件放弃作为第一响应者
    [self.nameField resignFirstResponder];
    //让placeField放弃作为第一响应者
    [self.placeField resignFirstResponder];
}

//完成输入后关闭键盘
- (IBAction)editEnd:(id)sender {
    //sender放弃作为第一响应者
    [sender resignFirstResponder];
}
@end
